from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.views.generic.base import View
#引入模型
from .models import UserProfile, EmailVerifyRecord
from .forms import LoginForm, RegisterForm, ForgetForm
#引入发送邮件类
from untils.email_send import send_register_email
#引入密码加密
from django.contrib.auth.hashers import make_password
# Create your views here.


class CustomBackend(ModelBackend):
	#自定义邮箱与账号登录功能
	def authenticate(self, username=None, password=None, **kwargs):
		try:
			#会用username或者email对传入的username进行匹
			user=UserProfile.objects.get(Q(username=username) | Q(email=username))
			if user.check_password(password):
				return user
		except Exception as e:
			return None



class LoginView(View):
	"""登录功能"""
	#get请求
	def get(self, request):
		return render(request, "login.html", {})
	#post请求	
	def post(self, request): 
		login_form=LoginForm(request.POST)  #实例化表单认证类，将用户post提交的数据传入进行认证
		if login_form.is_valid():           #判断认证是否成功
			#输入通过loginFrom验证,链接数据库验证
			tong_guo=login_form.cleaned_data
			#取用户输入值
			user_name=request.POST.get("username", "")
			pass_word=request.POST.get("password", "")
			#验证密码和账号是否正确
			user=authenticate(username=user_name, password=pass_word)
			if user is not None:
				login(request, user)
				request.session['state']=True
				request.session['username']=user_name
				return render(request,"index.html")
			else:
				return render(request, "login.html", {"msg":"用户名密码错误！"})
		else:
			return render(request, "login.html", {"login_form":login_form})

class logoutView(View):
	"""docstring for logout"""
	def get(self, request):
		try:
			request.session.flush()
		except KeyError:
			pass

		return redirect('/index.html')
	def post(self, request):
		pass

		
#注册视图
class RegisterView(View):
	def get(self, request):
		register_form=RegisterForm() #实例化
		return render(request, "register.html", {'register_form':register_form})

	def post(self, request):
		register_form=RegisterForm(request.POST)
		if register_form.is_valid():
			user_name=request.POST.get("email", "")
			pass_word=request.POST.get("password", "")
			#实例化user模型
			user_profile=UserProfile()
			user_profile.username=user_name
			user_profile.email=user_name
			user_profile.password=make_password(pass_word)
			#发送邮件
			send_register_email(user_name, "register") #发送邮件
			return render(request, "login.html")
		else: ## 如果验证失败, 则返回注册页面, 并返回register_form的错误信息
			return render(request, "register.html", {'register_form':register_form})
#激活用户的view
class ActiveUserView(View):
	"""docstring for ClassName"""
	def get(self, request, active_code):
		#查询邮箱验证码是否存在
		all_record=EmailVerifyRecord.objects.filter(code = active_code)
		#激活form负责给激活跳转进来的加验证码
		#active_form=
		#如果不为空
		if all_record:
			for record in all_record:
				#获取对应邮箱
				email=record.email
				#查找到邮箱对应的user
				user=UserProfile.objects.get(email=email)
				user.is_active=True
				user.save()
				#激活成功跳到登录页
				return render(request, "login.html", {})
		else:
			return render(request, "active_fail.html")
		
		
#用户忘记密码处理view
class ForgetPwdView(View):
	def get(self, request):
		forget_form=ForgetForm()
		return render(request, "forgetpwd.html",{'forget_form':forget_form})

	def post(self, request):
		forget_form=ForgetForm(request.POST)
		if forget_form.is_valid():
			email=request.POST.get('email', '')
			send_register_email(email,'forget')
			return render(request, 'send_success.html')
		else:
			return render(request, 'forgetpwd.html', {'forget_form':forget_form})
#用户重置密码
class ResetView(View):
	def get(self, request, active_code):
		all_record=EmailVerifyRecord.objects.filter(code=active_code)
		if all_record:
			for record in all_record:
				email=record.email
				return render(request, "password_reset.html", {"email":email})
		else:
			return render(request, "active_fail.html",{})
		return render(request, "login.html", {})
		